package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import com.cn.mmd.tools.SplitSpring;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 考勤
 * Created by Administrator on 2016/7/6 0006.
 */

@Controller
@RequestMapping(value = "page/attendance")
public class AttendanceController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseStuAttendanceService courseStuAttendanceService;

    @Autowired
    private StudentAppService studentAppService;

    @Autowired
    private TokenController tokenController;

    private SplitSpring splitSpring = new SplitSpring();

    /**
     * 本节考勤   数据库数据杂乱可能存在问题
     *
     * @return
     */
    @RequestMapping(value = "/select")
    public synchronized
    @ResponseBody
    Object selectAttendance(HttpServletRequest request) {
        Map<String, Object> map1 = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        List<Student> student;
        CourseStuAttendance courseStuAttendance;
        Integer cdid = Integer.parseInt(request.getParameter("courseWeeklyId"));
        String czid = request.getParameter("courseId");
        String teacherId = request.getParameter("teacherId");
        String token = request.getParameter("token");
        String className = request.getParameter("className");
        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData != null) {
            String cteacher = teacherData.getTeachername();
            Course classs;
            String attendance;
            StudentApp studentApp;
            Map<String, Object> map;
            int n = 1;
            Course course = new Course(czid, cteacher);
            int num = 0;
            if (className.equals("")) {
                classs = courseService.selectClass(course);
                for (int i1 = 0; i1 < splitSpring.splitSpringBy(classs.getCourseclasss(), 0, 0, ",", n).length; i1++) {
                    student = studentService.selectByClass(splitSpring.splitSpringBy(classs.getCourseclasss(), 0, 0, ",", n)[i1]);
                    if (student != null) {
                        num = num + student.size();
                        for (int i2 = 0; i2 < student.size(); i2++) {
                            map = new HashMap<String, Object>();
                            courseStuAttendance = new CourseStuAttendance(student.get(i2).getStudentid(), cdid);
                            courseStuAttendance = courseStuAttendanceService.selectByCouIdStuId(courseStuAttendance);
                            if (courseStuAttendance == null) {
                                attendance = "0";
                            } else {
                                attendance = courseStuAttendance.getAttendancecontent();
                            }
                            map.put("studentId", student.get(i2).getStudentid());
                            studentApp = studentAppService.selectByPrimaryKey(student.get(i2).getStudentid());
                            if (studentApp.getStudentheadportrait() != null) {
                                map.put("studentHeadPortrait", studentApp.getStudentheadportrait());
                            } else {
                                map.put("studentHeadPortrait", "");
                            }
                            map.put("studentName", student.get(i2).getStudentname());
                            map.put("attendance", attendance);
                            map.put("courseClass", splitSpring.splitSpringBy(classs.getCourseclasss(), 0, 0, ",", n)[i1]);
                            mapList.add(map);
                        }
                    }
                }
            } else {
                student = studentService.selectByClass(className);
                if (student != null) {
                    num = student.size();
                    for (int i2 = 0; i2 < student.size(); i2++) {
                        map = new HashMap<String, Object>();
                        courseStuAttendance = new CourseStuAttendance(student.get(i2).getStudentid(), cdid);
                        courseStuAttendance = courseStuAttendanceService.selectByCouIdStuId(courseStuAttendance);
                        if (courseStuAttendance == null) {
                            attendance = "0";
                        } else {
                            attendance = courseStuAttendance.getAttendancecontent();
                        }
                        map.put("studentId", student.get(i2).getStudentid());
                        studentApp = studentAppService.selectByPrimaryKey(student.get(i2).getStudentid());
                        if (studentApp.getStudentheadportrait() != null) {
                            map.put("studentHeadPortrait", studentApp.getStudentheadportrait());
                        } else {
                            map.put("studentHeadPortrait", "");
                        }
                        map.put("studentName", student.get(i2).getStudentname());
                        map.put("attendance", attendance);
                        map.put("courseClass", className);
                        mapList.add(map);
                    }
                }
            }

            if (mapList != null && mapList.size() > 0) {
                map1.put("code", 200);
                map1.put("data", mapList);
                map1.put("total", num);
                map1.put("message", "成功");
            } else {
                map1.put("code", 201);
                map1.put("message", "失败没有数据");
            }
        } else {
            map1.put("code", 202);
            map1.put("message", "此角色无法做次操作");
        }
        return map1;
    }

    /**
     * 设置考勤信息
     *
     * @return
     */
    @RequestMapping(value = "/add")
    public synchronized
    @ResponseBody
    Object addAttendance(HttpServletRequest request) {
        String stu = request.getParameter("student");
        Integer courseid = Integer.parseInt(request.getParameter("courseWeeklyId"));
        String courseId = request.getParameter("courseId");
        String teacherId = request.getParameter("teacherId");
        String token = request.getParameter("token");
        TeacherData teacherData;
        System.out.println("Attendance");
        System.out.println(stu);
        System.out.println(courseid);
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        if (teacherData != null) {
            List<Map> mapList = new ArrayList<Map>();
            Map<String, Object> map;
            String stuid;
            String classid;
            JSONArray jsonArray = JSONArray.fromObject(stu);
            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    String attendancecontent;
                    String major;
                    String collage;
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    stuid = jsonObject.getString("studentId");
                    attendancecontent = jsonObject.getString("attendanceContent");
                    map = new HashMap<String, Object>();
                    if (studentService.selectByPrimaryKey(stuid) != null) {
                        classid = studentService.selectByPrimaryKey(stuid).getStudentclass();
                        major = studentService.selectByPrimaryKey(stuid).getStudentmajor();
                        collage = studentService.selectByPrimaryKey(stuid).getStudentcollege();
                    } else {
                        classid = "";
                        major="";
                        collage="";
                    }
                    CourseStuAttendance courseStuAttendance = new CourseStuAttendance(stuid, courseid);
                    courseStuAttendance = courseStuAttendanceService.selectByCouIdStuId(courseStuAttendance);
                    if (courseStuAttendance == null) {
                        Date date = new Date();
                        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String logTime = time.format(date);
                        courseStuAttendance = new CourseStuAttendance(stuid, teacherId, classid, attendancecontent, courseid, courseId,logTime);
                        courseStuAttendance.setStudentmajor(major);
                        courseStuAttendance.setStudentcollege(collage);
                        courseStuAttendanceService.insertSelective(courseStuAttendance);
                    } else {
//                        if (courseStuAttendance.getAttendancecontent().equals("1") &&
//                                attendancecontent.equals("2")) {
//                            attendancecontent = "1,2";
//                            courseStuAttendance = new CourseStuAttendance(courseStuAttendance.getAttendanceid(), stuid, teacherId, classid, attendancecontent, courseid, courseId);
//                            courseStuAttendanceService.updateByPrimaryKeySelective(courseStuAttendance);
//                        } else {
                        CourseStuAttendance courseStuAttendance1 = new CourseStuAttendance();
                        courseStuAttendance1.setAttendanceid(courseStuAttendance.getAttendanceid());
                        courseStuAttendance1.setAttendancecontent(attendancecontent);
                        courseStuAttendance1.setStudentmajor(major);
                        courseStuAttendance1.setStudentcollege(collage);
                        courseStuAttendance1.setClassid(classid);
                        courseStuAttendanceService.updateByPrimaryKeySelective(courseStuAttendance1);
//                        }
                    }
                    mapList.add(map);
                }

                if (mapList != null && mapList.size() > 0) {
                    objectMap.put("message", "成功");
                    objectMap.put("code", 200);
//                    objectMap.put("data", mapList);
                } else {
                    objectMap.put("message", "数据获取错误");
                    objectMap.put("code", 201);
                }
            }
        } else {
            objectMap.put("message", "此用户没有权限做此操作");
            objectMap.put("code", 203);
        }
        return objectMap;
    }

    /**
     * 考勤统计
     *
     * @return
     */
    @RequestMapping(value = "/selectAll")
    public synchronized
    @ResponseBody
    Object selectAll(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        String stuid;
        String courseId = request.getParameter("courseId");
        String teacherId = request.getParameter("teacherId");
        String className = request.getParameter("className");
        String token = request.getParameter("token");
        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData != null) {
            int num;
            CourseStuAttendance courseStuAttendance;
//            courseStuAttendance.setCoursezid(courseId);
//            courseStuAttendance.setTeacherid(teacherId);
//            courseStuAttendance.setClassid(className);
//            List<CourseStuAttendance> courseStuAttendanceList = courseStuAttendanceService.selectByCouId(courseStuAttendance);
            List<Student> studentList = studentService.selectByClass(className);
            if (studentList != null && studentList.size() > 0) {
                StudentApp studentApp;
                for (int i = 0; i < studentList.size(); i++) {
                    stuid = studentList.get(i).getStudentid();
                    map = new HashMap<String, Object>();
                    courseStuAttendance = new CourseStuAttendance(stuid, "1", courseId);
                    if (courseStuAttendanceService.countByCouIdStuId(courseStuAttendance) > 0) {
                        num = courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
                        map.put("LateNum", num);
                    } else {
                        map.put("LateNum", "0");
                    }
                    courseStuAttendance = new CourseStuAttendance(stuid, "2", courseId);
                    if (courseStuAttendanceService.countByCouIdStuId(courseStuAttendance) > 0) {
                        num = courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
                        map.put("leaveEarlyNum", num);
                    } else {
                        map.put("leaveEarlyNum", "0");
                    }
//                        courseStuAttendance = new CourseStuAttendance(stuid, "迟到,早退", courseId);
//                        if (courseStuAttendanceService.countByCouIdStuId(courseStuAttendance) > 0) {
//                            num1 = courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
//                            courseStuAttendance = new CourseStuAttendance(stuid, "迟到", courseId);
//                            num = num1 + courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
//                            map.put("LateNum", num);
//                            courseStuAttendance = new CourseStuAttendance(stuid, "早退", courseId);
//                            num = num1 + courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
//                            map.put("leaveEarlyNum", num);
//                        }
                    courseStuAttendance = new CourseStuAttendance(stuid, "3", courseId);
                    if (courseStuAttendanceService.countByCouIdStuId(courseStuAttendance) > 0) {
                        num = courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
                        map.put("truantNum", num);
                    } else {
                        map.put("truantNum", "0");
                    }

                    courseStuAttendance = new CourseStuAttendance(stuid, "4", courseId);
                    if (courseStuAttendanceService.countByCouIdStuId(courseStuAttendance) > 0) {
                        num = courseStuAttendanceService.countByCouIdStuId(courseStuAttendance);
                        map.put("leaveNum", num);
                    } else {
                        map.put("leaveNum", "0");
                    }
                    studentApp = studentAppService.selectByPrimaryKey(stuid);
                    map.put("studentId", stuid);

                    if (studentApp != null) {
                        map.put("studentUrl", studentApp.getStudentheadportrait());
                        map.put("studentName", studentApp.getStudentname());
                        mapList.add(map);
                    }
                }

            }
            if (mapList != null && mapList.size() > 0) {
                objectMap.put("code", 200);
                objectMap.put("message", "查看成功");
                objectMap.put("data", mapList);
            } else {
                objectMap.put("code", 201);
                objectMap.put("message", "此班级没有学生");
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "此用户没有权限做此操作");
        }

        return objectMap;
    }

    @RequestMapping(value = "/selectClass")
    public synchronized
    @ResponseBody
    Object selectClass(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        String courseId = request.getParameter("courseId");
        String teacherId = request.getParameter("teacherId");
        String token = request.getParameter("token");
        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData != null) {
            Course course = new Course();
            course.setCourseid(courseId);
            course = courseService.selectClass(course);
            if (course != null) {
                String[] classs = course.getCourseclasss().split(",");
                if (classs != null && classs.length > 0) {
                    for (int i = 0; i < classs.length; i++) {
                        Map<String, Object> map1 = new HashMap<String, Object>();
                        map1.put("classId", classs[i]);
                        mapList.add(map1);
                    }
                    map.put("data", mapList);
                    map.put("code", 200);
                    map.put("message", "成功");
                } else {
                    map.put("code", 201);
                    map.put("message", "此课程没有班级上课");
                }
            } else {
                map.put("code", 202);
                map.put("message", "此课程id没有对应的课程,此课程不存在");
            }
        } else {
            map.put("code", 203);
            map.put("message", "此用户没有权限做此操作");
        }
        return map;
    }
}
